package com.sstir.doctor.config;

import com.alibaba.fastjson.JSONObject;
import com.sstir.doctor.utils.HttpUtil;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;

/**
 * @ClassName WebLogAspect
 * @Description   监控web请求统一打印日志
 * @Author hanjunjun
 * @Date 2020/4/27 16:00
 */
@Component
@Slf4j
@Aspect
@NoArgsConstructor
public class WebLogAspect {
    //进入方法时间戳
    private Long startTime;

    @Pointcut("execution(public * com.sstir.doctor.controller.*.*(..))")
    public void webLogPointCut() {
    }

    /**
     * @Author hanjunjun
     * @Description   前置通知：
     *                  目标方法执行之前执行   设置请求时间 请求参数
     * @Date 2020/4/14 14:19
     * @Param [joinPoint]
     * @return void
     **/
    @Before("webLogPointCut()")
    public void doBefore(JoinPoint joinPoint){
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        //获取请求头中的User-Agent
        UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
        //打印请求的内容
        startTime = System.currentTimeMillis();
        log.info("\n----------------------------------request start-----------------------------------------" +
                "\n服务名: sxpt-pay" + "\t请求Url：{}" + "\t请求方法: {}" + "\t请求参数: {}" + "\t请求方式: {}"
                + "\n请求开始时间: {}" + "\t请求ip：{} " + "\t浏览器：{}" + "\t浏览器版本：{}" + "\t操作系统: {}" ,
                request.getRequestURI(), joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()),
                request.getMethod(), LocalDateTime.now(), HttpUtil.getRealIp(request), userAgent.getBrowser().toString(),
                userAgent.getBrowserVersion(), userAgent.getOperatingSystem().toString());
    }

    /**
     * 返回通知：
     * 1. 在目标方法正常结束之后执行
     * 1. 在返回通知中补充请求日志信息，如返回时间，方法耗时，返回值，并且保存日志信息
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLogPointCut()")
    public void doAfterReturning(Object ret) throws Throwable {
        long endTime = System.currentTimeMillis();
        log.info("\n请求结束时间: {}" + "\t请求耗时: {}ms " + "\t请求返回: {}",LocalDateTime.now(),
                (endTime - startTime), JSONObject.toJSONString(ret) +
                "\n----------------------------------request end-------------------------------------------");

    }

    /**
     * 异常通知：
     * 1. 在目标方法非正常结束，发生异常或者抛出异常时执行
     * 1. 在异常通知中设置异常信息，并将其保存
     *
     * @param throwable
     */
    @AfterThrowing(value = "webLogPointCut()", throwing = "throwable")
    public void doAfterThrowing(Throwable throwable) {
        LocalDateTime.now();
        // 保存异常日志记录
        log.error("\n发生异常时间: {}" + "\n抛出异常: {}", LocalDateTime.now(), throwable.getMessage() +
                "\n----------------------------------request end-------------------------------------------");
    }

}
